//
//  AppDelegate.m
//  jungoo
//
//  Created by Dang Quang Trung on 7/24/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"
#import "Reachability.h"
#import "LoginViewController.h"
#import <Three20/Three20.h> 

@interface AppDelegate()
@property (nonatomic, retain) Reachability* reachability;
@end


@implementation AppDelegate

@synthesize window;
@synthesize viewController;
@synthesize reachability;
@synthesize logined;
@synthesize user;
@synthesize facebook,operation;
@synthesize locationManager = _locationManager;

#pragma mark -
#pragma mark share delegate

+ (AppDelegate*) shareDelegate
{
	return (AppDelegate*) [[UIApplication sharedApplication] delegate];
}

- (void)asyncLoadData
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
    
    dispatch_async(queue, ^{
        
        NSError *error = nil;
        NSArray *objects = [JGoAPI getUniversity:&error];
        
        if (error) {
            LOG(@"%@",[error localizedDescription]);
        }
        else {
            [JGoUtility setUniversities:objects];            
        }
        
        error = nil;        
        objects = [JGoAPI getCourses:&error];
        
        if (error) {
            LOG(@"%@",[error localizedDescription]);
        }
        else {
            [JGoUtility setCourses:objects];            
        }

        error = nil;
        objects = [JGoAPI getColleges:&error];
        
        if (error) {
            LOG(@"%@",[error localizedDescription]);
        }
        else {
            [JGoUtility setColleges:objects];            
        }        
        
        error = nil;
        objects = [JGoAPI getModules:&error];
        
        if (error) {
            LOG(@"%@",[error localizedDescription]);
        }
        else {
            [JGoUtility setModules:objects];            
        }
        
        [JGoUtility sharedUCCM];
    });    
}

- (void) handleNetworkChange:(NSNotification *)notice
{
	NetworkStatus remoteHostStatus = [self.reachability currentReachabilityStatus];
	
	if(remoteHostStatus == NotReachable) {
		NSLog(@"no");
		NSString *msg = @"Appserver is not reachable! This requires Internet connectivity.";
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Network Problem" 
                                                        message:msg 
                                                       delegate:nil 
                                              cancelButtonTitle:@"OK" 
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
	}
	else if (remoteHostStatus == ReachableViaWiFi) {
		NSLog(@"wifi");
		//[self.downloadQueue setMaxConcurrentOperationCount:4];
	}
	else if (remoteHostStatus == ReachableViaWWAN) {
		NSLog(@"cell");
		//[self.downloadQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
	}
}

- (void)startLocation
{
    if (_locationManager == nil) {
        self.locationManager = [[[CLLocationManager alloc] init] autorelease];
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = [[NSNumber numberWithDouble:kCLLocationAccuracyNearestTenMeters]doubleValue];                
    }
    
    [self.locationManager startUpdatingLocation];     
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    lockObject = [[NSLock alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(appUpdateLocation:) 
                                                 name:JGO_APP_UPDATE_LOCATION object:nil];
    [NSThread detachNewThreadSelector:@selector(keepAliveThread) toTarget:self withObject:nil];        
    
    [self asyncLoadData];
    [self startLocation];
    self.viewController = [[[LoginViewController alloc] initWithNibName:@"LoginViewController" 
                                                                 bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
    
    facebook = [[Facebook alloc] initWithAppId:FB_APP_ID andDelegate:(id)self];
    
    [self.window makeKeyAndVisible];
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    if ([prefs objectForKey:@"FBAccessTokenKey"] 
        && [prefs objectForKey:@"FBExpirationDateKey"]) {
        facebook.accessToken = [prefs objectForKey:@"FBAccessTokenKey"];
        facebook.expirationDate = [prefs objectForKey:@"FBExpirationDateKey"];
    }
    
    /*
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNetworkChange:) name:kReachabilityChangedNotification object:nil];
	
	self.reachability = [Reachability reachabilityForInternetConnection];
	[self.reachability startNotifier];
     */
    
    // If you hit this assertion it's because a massive file is about to be downloaded.
    // If you're sure you want to do this, add the following line to your app delegate startup
    // method. Setting the max content length to zero allows anything to go through. If you just
    // want to raise the limit, set it to any positive byte size.
    [[TTURLRequestQueue mainQueue] setMaxContentLength:0];
    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [self.facebook handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [self.facebook handleOpenURL:url];
}
-(void)gotoHome
{
    [self showLoadingView];        
    operation = [[FacebookConnectOperation alloc] initWithFacebook:self.facebook] ;
    operation.viewController = self.viewController;
    [operation readFacebookData:nil];
}
- (void)fbDidLogin {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[facebook accessToken] forKey:@"FBAccessTokenKey"];
    [defaults setObject:[facebook expirationDate] forKey:@"FBExpirationDateKey"];
    [defaults synchronize]; 
    [self gotoHome];
    
}

-(void)fbDidExtendToken:(NSString *)accessToken expiresAt:(NSDate *)expiresAt {
    NSLog(@"token extended");
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];   
    [defaults setObject:accessToken forKey:@"FBAccessTokenKey"];
    [defaults setObject:expiresAt forKey:@"FBExpirationDateKey"];
    [defaults synchronize];   
    
}
-(void)changeUser {
    
    //check to see if condition is valid
    if([facebook isSessionValid]){
        [facebook logout];
    }
    
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    [prefs removeObjectForKey:@"FBAccessTokenKey"];
    [prefs removeObjectForKey:@"FBExpirationDateKey"];
    
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    
    
}
- (void)fbDidLogout {
    facebook.accessToken = nil; 
    facebook.expirationDate = nil;
    /*
    NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage]; 
    NSArray* facebookCookies = [cookies cookiesForURL: [NSURL URLWithString:@"http://login.facebook.com"]]; 
    for (NSHTTPCookie* cookie in facebookCookies) { 
        [cookies deleteCookie:cookie]; 
    }
    
    NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage]; 
    for (NSHTTPCookie* cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) 
    { 
        [cookies deleteCookie:cookie]; 
        
    }
     */
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    [prefs removeObjectForKey:@"FBAccessTokenKey"];
    [prefs removeObjectForKey:@"FBExpirationDateKey"];
    [prefs removeObjectForKey:@"FBExpirationDateKey"];
    
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies])
    {
        NSString* domainName = [cookie domain];
        NSRange domainRange = [domainName rangeOfString:@"facebook"];
        if(domainRange.length > 0)
        {
            [storage deleteCookie:cookie];
        }
    }

}


- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)appUpdateLocation:(NSNotification*)notication
{
    [self startLocation];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [self startLocation];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}

- (void)dealloc 
{
	[viewController release];
	[window release];
    [facebook release];
    [operation release];
    [self setLocationManager:nil];
	[super dealloc];
}

#pragma mark -
#pragma mark Location Manage Delegate

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{    
    [JGoUtility setLocation:newLocation];
    [_locationManager stopUpdatingLocation];
        
    LOG(@"lat :%f, lon : %f",newLocation.coordinate.latitude,newLocation.coordinate.longitude);
    
    [[NSNotificationCenter defaultCenter] postNotificationName:JGO_APP_DID_UPDATE_LOCATION object:nil];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error 
{    
    if ([error code] != kCLErrorLocationUnknown) {
        [_locationManager stopUpdatingLocation];
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:JGO_APP_DID_UPDATE_LOCATION object:nil];
}

#pragma mark -
#pragma mark Public methods


- (void)showLoadingView
{
    if (loadingView == nil)
    {
        loadingView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 480.0)];
        loadingView.opaque = NO;
        loadingView.backgroundColor = [UIColor darkGrayColor];
        loadingView.alpha = 0.5;
		
        UIActivityIndicatorView *spinningWheel = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(142.0, 222.0, 37.0, 37.0)];
        [spinningWheel startAnimating];
        spinningWheel.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
        [loadingView addSubview:spinningWheel];
        [spinningWheel release];
    }
    
    [window addSubview:loadingView];
}

- (void)hideLoadingView
{
    [loadingView removeFromSuperview];
}

- (void)keepAliveThread
{    
    while (YES) {
        
        [[JGoUtility sharedLock] lock];
        NSString *userId = [[JGoUtility sharedCreateAccount] objectForKey:@"user_id"];                        
        
        if ([userId length]) {
            
            [JGoAPI keepAliveForUserId:userId error:nil];
            sleep(3);
        }
        else {
            sleep(5);
        }  
        
        [[JGoUtility sharedLock] unlock];        
    }
}

@end

@implementation UINavigationBar (CUstomImage)

- (void)drawRect:(CGRect)rect{
	UIImage *image = [UIImage imageNamed:@"bckgNavigationBar.png"];
	[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}

@end

